package org.juggers.component;

/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;

/**
 * @author <a href="mailto:michel@breizhjug.org">Michel DAVID</a>
 */
@Component( "captcha" )
public class DefaultCaptcha
    implements Captcha
{
    private static Log logger = LogFactory.getLog( DefaultCaptcha.class );

    // reCaptcha "invalid solution" error
    private static final String INVALID_SOLUTION = "incorrect-captcha-sol";

    private String publicKey;

    private String privateKey;

    private String theme;

    private String lang;

    private String tabIndex;

    /**
     * {@inheritDoc}
     * 
     * @see org.juggers.component.Captcha#getHtml()
     */
    public String getHtml()
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append( "<script type=\"text/javascript\" src=\"http://api.recaptcha.net/challenge?k=" );
        buffer.append( publicKey ).append( "\"></script>" );
        buffer.append( "<script>var RecaptchaOptions = { " );
        buffer.append( "theme : '" ).append( theme ).append( "'," );
        buffer.append( "lang : '" ).append( lang ).append( "'," );
        buffer.append( "tabindex : " ).append( tabIndex );
        buffer.append( "}; </script>" );
        return buffer.toString();
    }

    /**
     * {@inheritDoc}
     * 
     * @see org.juggers.component.Captcha#isValid(java.lang.String, java.lang.String, java.lang.String)
     */
    public boolean isValid( String challenge, String response, String remoteAddr )
    {
        try
        {
            URL url = new URL( "http://api-verify.recaptcha.net/verify" );
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput( true );
            connection.setRequestMethod( "POST" );

            OutputStreamWriter writer = new OutputStreamWriter( connection.getOutputStream() );
            writer.write( getPostParameters( challenge, response, remoteAddr ) );
            writer.close();

            if ( connection.getResponseCode() == HttpURLConnection.HTTP_OK )
            {
                BufferedReader reader = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
                try
                {
                    boolean valid = Boolean.parseBoolean( reader.readLine() );
                    if ( valid )
                    {
                        return true;
                    }

                    String errorCode = reader.readLine();
                    if ( !INVALID_SOLUTION.equals( errorCode ) )
                    {
                        logger.error( "reCaptcha Error " + errorCode );
                    }
                }
                finally
                {
                    reader.close();
                }
            }
            else
            {
                logger.error( "reCaptcha HTTP Error " + connection.getResponseCode() );
            }
        }
        catch ( MalformedURLException ex )
        {
            logger.error( "reCaptcha MalformedURLException " + ex.getMessage() );
        }
        catch ( IOException ex )
        {
            logger.error( "reCaptcha IOException " + ex.getMessage() );
        }
        return false;
    }

    /**
     * Create the POST parameters string
     * 
     * @param challenge Captcha challenge
     * @param response Captcha response
     * @param remoteAddr Remote address
     * @return Parameters string
     * @throws UnsupportedEncodingException Encoding exception
     */
    private String getPostParameters( String challenge, String response, String remoteAddr )
        throws UnsupportedEncodingException
    {
        StringBuffer buffer = new StringBuffer();
        buffer.append( "privatekey=" ).append( URLEncoder.encode( privateKey, "UTF-8" ) );
        buffer.append( "&remoteip=" ).append( URLEncoder.encode( remoteAddr, "UTF-8" ) );
        buffer.append( "&challenge=" ).append( URLEncoder.encode( challenge, "UTF-8" ) );
        buffer.append( "&response=" ).append( URLEncoder.encode( response, "UTF-8" ) );
        return buffer.toString();
    }

    public void setPublicKey( String publicKey )
    {
        this.publicKey = publicKey;
    }

    public void setPrivateKey( String privateKey )
    {
        this.privateKey = privateKey;
    }

    public void setTheme( String theme )
    {
        this.theme = theme;
    }

    public void setLang( String lang )
    {
        this.lang = lang;
    }

    public void setTabIndex( String tabIndex )
    {
        this.tabIndex = tabIndex;
    }
}
